//
//  MusicPlayerViewController.m
//  MarianasTrench
//
//  Created by 王晓晨 on 16/3/22.
//  Copyright © 2016年 王爵. All rights reserved.
//

#import "MusicPlayerViewController.h"

@interface MusicPlayerViewController ()

@property (nonatomic, strong) UIImageView *bigImage;/**< 大播放背景图 >*/
@property (nonatomic, strong) AMBlurView *blurView;/**< 毛玻璃效果 >*/
@property (nonatomic, strong) UILabel *albumLabel;/**< 专辑标题 >*/
@property (nonatomic, strong) UILabel *titleLabel;/** 音频标题 */

@property (nonatomic, strong) UIImageView *photoImage;/**< 播放界面图片 >*/
@property (nonatomic, assign) BOOL isPlay;/**< 是否播放状态 >*/
@property (nonatomic, strong) UISlider *slider;/**< 进度条 >*/
@property (nonatomic, strong) UIButton *playButton;/**< 播放按钮 >*/
@property (nonatomic, strong) UIButton *nextButton;/**< 下一个按钮 >*/
@property (nonatomic, strong) UIButton *forwardButton;/**< 前一个 >*/
@property (nonatomic, assign) CGFloat totalDuration;/**< 总时间 >*/
@property (nonatomic, strong) UILabel *currentTime;/**< 总时间显示 >*/
@property (nonatomic, strong) UILabel *totalTime;/**< 当前播放时间显示 >*/

@property (nonatomic, strong) AVPlayer *player;/**< 播放器 >*/
@property (nonatomic, strong) AVPlayerItem *playerItem;/**< 播放项目 >*/

@end

@implementation MusicPlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];

}

- (void)viewWillAppear:(BOOL)animated {
    
    if ([PlayMusic sharePlayMusic].isPlayState == NO) {
        ListenModel *model = _playMusicArr[self.indexNum];
        if (model.playUrl32.length > 0) {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playUrl32];
        }
        else {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playPath32];
        }
    }
    else {
        [[PlayMusic sharePlayMusic] pause];
        [PlayMusic sharePlayMusic].urlStr = nil;
        ListenModel *model = _playMusicArr[self.indexNum];
        if (model.playUrl32.length > 0) {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playUrl32];
        }
        else {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playPath32];
        }
    }
    
    [PlayMusic sharePlayMusic].playToEndBlock = ^() {
        
        [self.player pause];
        self.indexNum += 1;
        if (_indexNum >= _playMusicArr.count - 1) {
            self.indexNum = _playMusicArr.count - 1;
        }
        ListenModel *model = self.playMusicArr[self.indexNum];
        [PlayMusic sharePlayMusic].urlStr = nil;
        if (model.playUrl32.length > 0) {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playUrl32];
            [self.bigImage HANDLEIMAGE(model.coverLarge)];
            [self.photoImage HANDLEIMAGE(model.coverMiddle)];
        }
        else {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playPath32];
            [self.bigImage HANDLEIMAGE(model.albumCover)];
            [self.photoImage HANDLEIMAGE(model.albumCover)];
        }
        
        if (model.coverLarge.length > 0) {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"musicChange" object:model.coverLarge userInfo:nil];
        }
        else {
            [[NSNotificationCenter defaultCenter] postNotificationName:@"musicChange" object:model.albumCover userInfo:nil];
        }
        
        [self addPrograssObserver];
        
    };
    
    ListenModel *model = _playMusicArr[self.indexNum];
    
    /** 发送通知 */
    if (model.coverLarge.length > 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"musicChange" object:model.coverLarge userInfo:nil];
    }
    else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"musicChange" object:model.albumCover userInfo:nil];
    }

    
    [self addPrograssObserver];
    
    [self createSubViews];
}

#pragma mark - 创建子视图
- (void)createSubViews {
    
    ListenModel *model = _playMusicArr[self.indexNum];
    
    /** 大背景图 */
    self.bigImage = [[UIImageView alloc] initWithFrame:self.view.frame];
    if (model.coverLarge.length > 0) {
        [self.bigImage HANDLEIMAGE(model.coverLarge)];
    }
    else {
        [self.bigImage HANDLEIMAGE(model.albumCover)];
    }
    [self.view addSubview:_bigImage];
    
    [self setBlurView:[AMBlurView new]];
    [[self blurView] setFrame:_bigImage.frame];
    [[self blurView] setAutoresizingMask:UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleHeight];
    [_bigImage addSubview:[self blurView]];
    _blurView.alpha = 0.8;

    UIView *backView = [[UIView alloc] initWithFrame:_bigImage.frame];
    [self.view addSubview:backView];
    backView.backgroundColor = [UIColor blackColor];
    backView.alpha = 0.7;
    
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(40, 40, SCREEN_WIDTH - 80, 30)];
    if (model.title.length > 0) {
        self.titleLabel.text = [NSString stringWithFormat:@"%@", model.title];
    }
    else {
        self.titleLabel.text = [NSString stringWithFormat:@"%@", model.albumTitle];
    }
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    _titleLabel.font = [UIFont systemFontOfSize:20];
    _titleLabel.textColor = [UIColor whiteColor];
    [self.view addSubview:_titleLabel];
    
    /** 创建旋转图片 */
    self.photoImage = [[UIImageView alloc] initWithFrame:CGRectMake(50, SCREEN_HETGHT / 6, SCREEN_WIDTH - 100, SCREEN_WIDTH - 100)];
    
    if (model.coverMiddle.length > 0) {
        [self.photoImage HANDLEIMAGE(model.coverMiddle)];
    }
    else {
        [self.photoImage HANDLEIMAGE(model.albumCover)];
    }

    [self.view addSubview:_photoImage];
    _photoImage.layer.cornerRadius = (SCREEN_WIDTH - 100) / 2;
    _photoImage.layer.masksToBounds = YES;
    _photoImage.layer.borderColor = [UIColor redColor].CGColor;
    _photoImage.layer.borderWidth = 2;
    
    /** 以Z轴旋转 */
    CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"transform.rotation.z"];
    
    /** 旋转开始 */
    animation.fromValue = [NSNumber numberWithFloat:0];
    // 旋转的结束值
    // π 是180° 2π是360°
    animation.toValue = [NSNumber numberWithFloat:M_PI * 2];
    // 时间
    animation.duration = 10;
    // 重复次数
    // NSIntegerMax 一直在重复
    animation.repeatCount = NSIntegerMax;
    // 是否自动回到原来的位置
    animation.autoreverses = NO;
    // 是否按照结束位置继续旋转
    animation.cumulative = YES;
    [self.photoImage.layer addAnimation:animation forKey:@"标记"];
    /** 起始状态 */
    _isPlay = YES;
    
    /** 创建Slider */
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(50, _photoImage.frame.origin.y + _photoImage.frame.size.height + 50, SCREEN_WIDTH - 100, 30)];
    [self.view addSubview:_slider];
    [_slider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    _slider.minimumTrackTintColor = [UIColor redColor];
    
    /** 当前时间 */
    self.currentTime = [[UILabel alloc] initWithFrame:CGRectMake(10, _slider.frame.origin.y, 30, _slider.frame.size.height)];
    [self.view addSubview:_currentTime];
    _currentTime.textColor = [UIColor whiteColor];
    _currentTime.font = [UIFont systemFontOfSize:10];
    
    self.totalTime = [[UILabel alloc] initWithFrame:CGRectMake(_slider.frame.origin.x + _slider.frame.size.width + 10, _slider.frame.origin.y, 30, _slider.frame.size.height)];
    [self.view addSubview:_totalTime];
    _totalTime.textColor = [UIColor whiteColor];
    _totalTime.font = [UIFont systemFontOfSize:10];
    
    /** 播放按钮 */
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_playButton setImage:IMAGE(@"iconfont-bofang-2.png") forState:UIControlStateNormal];
    _playButton.frame = CGRectMake(SCREEN_WIDTH / 7 * 3, _slider.frame.origin.y + _slider.frame.size.height + 30, SCREEN_WIDTH / 7, SCREEN_WIDTH / 7);
    _playButton.layer.cornerRadius = SCREEN_WIDTH / 14;
    _playButton.layer.masksToBounds = YES;
    [self.view addSubview:_playButton];
    [_playButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    /** 下一曲按钮 */
    self.nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _nextButton.frame = CGRectMake(_playButton.frame.origin.x + _playButton.frame.size.width + 40, _playButton.frame.origin.y + (SCREEN_WIDTH / 7 - SCREEN_WIDTH / 11) / 2, SCREEN_WIDTH / 11, SCREEN_WIDTH / 11);
    [_nextButton setImage:IMAGE(@"iconfont-xiayiqu.png") forState:UIControlStateNormal];
    _nextButton.layer.cornerRadius = SCREEN_WIDTH / 22;
    _nextButton.layer.masksToBounds = YES;
    [self.view addSubview:_nextButton];
    [_nextButton addTarget:self action:@selector(nextButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_nextButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    /** 上一曲按钮 */
    self.forwardButton = [UIButton buttonWithType:UIButtonTypeCustom];
    _forwardButton.frame = CGRectMake(SCREEN_WIDTH / 7 * 3 - _nextButton.frame.size.width - 40, _nextButton.frame.origin.y, _nextButton.frame.size.width, _nextButton.frame.size.height);
    [_forwardButton setImage:IMAGE(@"iconfont-shangyiqu.png") forState:UIControlStateNormal];
    _forwardButton.layer.cornerRadius = SCREEN_WIDTH / 22;
    _forwardButton.layer.masksToBounds = YES;
    [self.view addSubview:_forwardButton];
    [_forwardButton addTarget:self action:@selector(forwardButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [_forwardButton addTarget:self action:@selector(playButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    backButton.frame = CGRectMake(10, 40, 30, 30);
    [backButton setImage:IMAGE(@"icon_back_h@2x.png") forState:UIControlStateNormal];
    [self.view addSubview:backButton];
    [backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
}


#pragma mark - 播放进度监听
- (void)addPrograssObserver {
    
    /** 跟随指针 */
    self.player = [PlayMusic sharePlayMusic].avPlayer;
    self.playerItem = [PlayMusic sharePlayMusic].avPlayItem;
    
    __strong typeof(self) weakSelf = self;
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        // 获取到总的视频时间.asac
        CGFloat duration = CMTimeGetSeconds(weakSelf.playerItem.duration);
        // 获取到当前时间
        CGFloat current = CMTimeGetSeconds(weakSelf.playerItem.currentTime);
        
        // 把总时间转化为字符串 显示在lable上
        NSString *durationT = [NSString stringWithFormat:@"%02d:%02d", (int)duration / 60, (int)duration % 60];
        NSString *currentT = [NSString stringWithFormat:@"%02d:%02d", (int)current / 60, (int)current % 60];
        
        weakSelf.currentTime.text = currentT;
        weakSelf.totalTime.text = durationT;
        
        weakSelf.totalDuration = duration;
        
        /** slider的值 */
        weakSelf.slider.value = current / duration;

    }];
    
}

#pragma mark - button点击方法

- (void)backButtonAction:(UIButton *)button {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)nextButtonAction:(UIButton *)button {
    self.indexNum += 1;
    if (_indexNum >= _playMusicArr.count - 1) {
        self.indexNum = _playMusicArr.count - 1;
    }
    ListenModel *model = _playMusicArr[self.indexNum];
    [PlayMusic sharePlayMusic].urlStr = nil;
    if ([PlayMusic sharePlayMusic].isPlayState == YES) {
        [self.player pause];
        if (model.playUrl32.length > 0) {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playUrl32];
            [self.bigImage HANDLEIMAGE(model.coverLarge)];
            [self.photoImage HANDLEIMAGE(model.coverMiddle)];
        }
        else {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playPath32];
            [self.bigImage HANDLEIMAGE(model.albumCover)];
            [self.photoImage HANDLEIMAGE(model.albumCover)];
        }
    }
    else {
        if (model.playUrl32.length > 0) {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playUrl32];
            [self.bigImage HANDLEIMAGE(model.coverLarge)];
            [self.photoImage HANDLEIMAGE(model.coverMiddle)];
        }
        else {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playPath32];
            [self.bigImage HANDLEIMAGE(model.albumCover)];
            [self.photoImage HANDLEIMAGE(model.albumCover)];
        }
    }

    /** 发送通知 */
    if (model.coverLarge.length > 0) {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"musicChange" object:model.coverLarge userInfo:nil];
    }
    else {
        [[NSNotificationCenter defaultCenter] postNotificationName:@"musicChange" object:model.albumCover userInfo:nil];
    }

    [self addPrograssObserver];
}

- (void)forwardButtonAction:(UIButton *)button {
    self.indexNum -= 1;
    if (_indexNum <= 0) {
        self.indexNum = 0;
    }
    ListenModel *model = _playMusicArr[self.indexNum];
    [PlayMusic sharePlayMusic].urlStr = nil;
    if ([PlayMusic sharePlayMusic].isPlayState == YES) {
        [self.player pause];
        if (model.playUrl32.length > 0) {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playUrl32];
            [self.bigImage HANDLEIMAGE(model.coverLarge)];
            [self.photoImage HANDLEIMAGE(model.coverMiddle)];
        }
        else {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playPath32];
            [self.bigImage HANDLEIMAGE(model.albumCover)];
            [self.photoImage HANDLEIMAGE(model.albumCover)];
        }
    }
    else {
        if (model.playUrl32.length > 0) {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playUrl32];
            [self.bigImage HANDLEIMAGE(model.coverLarge)];
            [self.photoImage HANDLEIMAGE(model.coverMiddle)];
        }
        else {
            [[PlayMusic sharePlayMusic] playMusicWithUrlStr:model.playPath32];
            [self.bigImage HANDLEIMAGE(model.albumCover)];
            [self.photoImage HANDLEIMAGE(model.albumCover)];
        }
    }
    
    /** 发送通知 */
    [self addPrograssObserver];
}

- (void)playButtonAction:(UIButton *)button {
    
    if (_isPlay == YES) {
        // 暂停
        [[PlayMusic sharePlayMusic] pause];
        
        [_playButton setImage:IMAGE(@"iconfont-bofang.png") forState:UIControlStateNormal];
        CFTimeInterval stopTime = [self.photoImage.layer convertTime:CACurrentMediaTime() fromLayer:nil];
        // 设置动画速度
        self.photoImage.layer.speed = 0;
        // 保存时间的偏移量
        self.photoImage.layer.timeOffset = stopTime;
        
    }
    else {
        // 继续
        [[PlayMusic sharePlayMusic] play];
        
        [_playButton setImage:IMAGE(@"iconfont-bofang-2.png") forState:UIControlStateNormal];
        // 找到时间偏移量
        CFTimeInterval stopTime = self.photoImage.layer.timeOffset;
        // 速度设置为1
        self.photoImage.layer.speed = 1;
        
        // 把beginTime重置
        self.photoImage.layer.beginTime = 0;
        self.photoImage.layer.timeOffset = 0;
        // 设置开始的时间
//                self.imgView.layer.beginTime = stopTime;
        self.photoImage.layer.beginTime = [self.photoImage.layer convertTime:CACurrentMediaTime() fromLayer:nil] - stopTime;
    }
    // 状态反转
    _isPlay = !_isPlay;
}

- (void)sliderAction:(UISlider *)slider {
    // 获取到当前进度时间
    CGFloat currentTime = self.totalDuration *slider.value;
    // 转化为CMTime
    CMTime dragTime = CMTimeMake(currentTime, 1);
    [self.player seekToTime:dragTime completionHandler:^(BOOL finished) {
        // 到了时间之后 开始播放
        [self.player play];
    }];
}

- (void)viewWillDisappear:(BOOL)animated {
    [PlayMusic sharePlayMusic].musicModelArr = [NSMutableArray arrayWithArray:_playMusicArr];
    [PlayMusic sharePlayMusic].indexNum = self.indexNum;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
